package com.nineclock.message.service.impl;

import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.message.config.JPushManager;
import com.nineclock.message.dto.NcMessageDTO;
import com.nineclock.message.pojo.NcMessage;
import com.nineclock.message.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    JPushManager pushManager;

    @Override
    public Boolean pushSingleMessage(NcMessage message) throws Exception {
        //1. 把收到的消息存储到mongoDb
        mongoTemplate.save(message);

        //推送消息给主管理员
        //1. 标题  ， 2.  推送的内容 3. 推送的目标 4. 自定义内容（null）
        pushManager.sendNotificationByAlias(message.getTitle(), message.getContent(), message.getTargets(),  null);

        return true;
    }

    @Override
    public List<NcMessage> findMessageRecord(NcMessageDTO messageDTO) {

        if(messageDTO == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //查询条件
        Query query = new Query();
        if(messageDTO.getId() != null){
            // id = 1
            query.addCriteria(Criteria.where("_id").is(messageDTO.getId()));
        }
        if(messageDTO.getType() != null){ //消息类型
            query.addCriteria(Criteria.where("messageType").is(messageDTO.getType()));
        }
        if(messageDTO.getTargetId() != null){ //审批人id
            query.addCriteria(Criteria.where("approveUserId").is(messageDTO.getTargetId()));
        }
        if(messageDTO.getUserId() != null){ //申请人id
            query.addCriteria(Criteria.where("applyUserId").is(messageDTO.getUserId()));
        }
        //根据审批状态 ，升序排序
        query.with(Sort.by(Sort.Direction.ASC, "approveStatue"));


        List<NcMessage> messageList = mongoTemplate.find(query, NcMessage.class);
        return messageList;
    }

    //根据mongo
    @Override
    public void updateMessageWithApproved(String messageId) {

        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(messageId));

        Update update = new Update();
        update.set("useStatus", 1);
        update.set("approveStatue", 1);


        //query 条件
        //update 要更新的数据
        mongoTemplate.updateFirst(query , update , NcMessage.class);
    }
}
